
#include "joystick.h"

#include <iostream>
#include <string>

#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>

using namespace std;


Joystick::Joystick(const char * device)
{
	fd= open(device, O_RDONLY | O_NONBLOCK); 
	if (fd < 0)
		cerr<<"Failed to open joystick: "<<device<<endl;
		        
}


Joystick::~Joystick()
{
	if(fd>0)
		close(fd);
}


void Joystick::Update()
{
	if(fd>0)
	{
		int bytes;
		joystick_event event;
		
		bytes = read(fd,&event,sizeof(event));
		
		if(bytes==-1)return; //there is no data to read
		
		if(bytes!=sizeof(event))
		{
			cerr<<"Unexpected joystick event size :"<<bytes<<endl;
			return;
		}
		
		event.type &=~0x80; /* remove init events */
		
		switch(event.type)
		{
			case 0x02: /* axis */
				axis[event.number] = event.value/32767.0f;
			break;
			
			case 0x01: /* button */
				buttons[event.number]=event.value;
			break;
		}
					
		
	}
}
